package com.atguigu.yuntai.monitor.service.impl;

import com.atguigu.yuntai.monitor.service.HiveMetaService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.hadoop.hive.conf.HiveConf;
import org.apache.hadoop.hive.metastore.IMetaStoreClient;
import org.apache.hadoop.hive.metastore.RetryingMetaStoreClient;
import org.apache.hadoop.hive.metastore.api.MetaException;
import org.apache.hadoop.hive.metastore.api.Table;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.List;

/**
 * <p>
 *     数据服务层
 *     访问hive元数据
 * </p>
 **/
@Service
@Slf4j
public class HiveMetaServiceImpl implements HiveMetaService {

    @Autowired
    @Qualifier("hiveMetaStoreConf")
    HiveConf hiveConf;

    IMetaStoreClient hiveMetaStoreClient;

    @PostConstruct
    public void createHiveMeatStoreClient() {
        try {
            hiveMetaStoreClient = RetryingMetaStoreClient.getProxy(hiveConf,false);
        } catch (MetaException e) {
            log.error("hive元数据客户端无法创建{}",e);
        }
    }

    /**
     * 查询hive上所有的数据库
     */
    @SneakyThrows
    @Override
    public List<String> queryAllDataBases() {
        return hiveMetaStoreClient.getAllDatabases();
    }

    /**
     * 查询一个数据库中所有的表
     */
    @SneakyThrows
    @Override
    public List<String> queryAllTables(String database) {
        return hiveMetaStoreClient.getAllTables(database);
    }

    /**
     * 查询一张表的详情
     */
    @SneakyThrows
    @Override
    public Table queryDetailOfOneTable(String database,String tableName) {
        return hiveMetaStoreClient.getTable(database, tableName);
    }
}
